import { ref, onMounted, onUnmounted } from 'vue';
const call = ref<any[]>([]);
let isInt = false
let resizeTimeout: number | null = null;

// 防抖函数
const debounce = (func: () => void, delay: number = 200) => {
  return () => {
    if (resizeTimeout) {
      clearTimeout(resizeTimeout);
    }
    resizeTimeout = window.setTimeout(() => {
      func();
    }, delay);
  };
};

export const useWindowResize = () => {
    const width = ref(window?.innerWidth);
    const height = ref(window?.innerHeight);

    const handleResize = () => {
        width.value = window?.innerWidth;
        height.value = window?.innerHeight;
        call.value.forEach((item: any) => {
            item({
                width: width.value,
                height: height.value,
            })
        })
    };

    const debouncedHandleResize = debounce(handleResize);

    onMounted(() => {
        if (typeof window !== 'undefined') {
            if (isInt) return
            isInt = true
            window?.addEventListener('resize', debouncedHandleResize);
        }
    });

    onUnmounted(() => {
        if (typeof window !== 'undefined') {
            if (resizeTimeout) {
              clearTimeout(resizeTimeout);
            }
            window?.removeEventListener('resize', debouncedHandleResize);
        }
    });
    return {
        width,
        height,
        resize: (callBlack: any) => {
            call.value.push(callBlack)
        }
    };
};